<template>
    <el-dialog
        v-model="showflag"
        :title="title"
        width="400"
        align-center
        @close="resetdata"
        :close-on-click-modal="false">
        <div style="padding: 0 40px">
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon>
                <!-- <el-form-item label="图片上传" prop="images">
                    <el-upload
                        class="avatar-uploader"
                        :action="baseURL + '/admin/Sundry/uploadFile'"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :headers="{
                            Admintoken: token,
                        }"
                        name="image">
                        <img v-if="ruleForm.images" :src="ruleForm.images" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item> -->
                <el-form-item label="分类名称" prop="materialName">
                    <el-input
                        v-model="ruleForm.materialName"
                        :disabled="!isedit"
                        placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="单价" prop="price">
                    <el-input
                        v-model="ruleForm.price"
                        :disabled="!isedit"
                        placeholder="请输入单价" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input
                        v-model="ruleForm.sort"
                        type="number"
                        :disabled="!isedit"
                        placeholder="请输入" />
                </el-form-item>
                <!-- <el-form-item label="单位" prop="unitName">
                    <el-input
                        v-model="ruleForm.unitName"
                        :disabled="!isedit"
                        placeholder="请输入单位" />
                </el-form-item>
                <el-form-item label="助记码" prop="mnemonic">
                    <el-input
                        v-model="ruleForm.mnemonic"
                        :disabled="!isedit"
                        placeholder="请输入助记码" />
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input
                        v-model="ruleForm.stock"
                        :disabled="!isedit"
                        placeholder="请输入库存" />
                </el-form-item>
                <el-form-item label="条形码" prop="barCode">
                    <el-input
                        v-model="ruleForm.barCode"
                        :disabled="!isedit"
                        placeholder="请输入条形码" />
                </el-form-item> -->
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showflag = false">取消</el-button>
                <el-button v-if="isedit" type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, provide, reactive, toRaw, inject } from "vue";
import { ElMessage } from "element-plus";
import { post, baseURL } from "../../../../api/request";
let showflag = ref(false);
let title = ref("新增分类");
let isedit = ref(true);
let device_id = ref("");
let token = ref("");
const getdata = inject<() => void>("getdata")!; //父组件的方法

onMounted(() => {
    token.value = localStorage.getItem("token")||'';
});


//表单相关---------------------------------------
import type { FormInstance, FormRules } from "element-plus";
interface RuleForm {
    id: string;
    images:string;
    materialName: string;
    price: string;
    sort:number;
    unitName: string;
    mnemonic: string;
    stock: string;
    barCode: string;
}

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
    id:'',
    images:'',
    materialName: "",
    price: "",
    sort:0,
    unitName: "",
    mnemonic: "",
    stock: "",
    barCode: "",
});

const rules = reactive<FormRules<RuleForm>>({
    images: [{ required: true, message: "请上传图片", trigger: "blur" }],
    materialName: [{ required: true, message: "请填写分类名称", trigger: "blur" }],
    price: [
        { required: true, message: "请填写单价", trigger: "blur" },
    ],
    unitName: [{ required: true, message: "请填写单位", trigger: "blur" }],
    mnemonic: [{ required: true, message: "请填写助记码", trigger: "blur" }],
    barCode: [{ required: true, message: "请填写条形码", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            post({
                url: ruleForm.id
                    ? "/api/types/edit"
                    : "/api/types/add",
                data: toRaw(ruleForm),
            }).then((res: any) => {
                ElMessage.success("操作成功!");
                getdata();
                showflag.value = false;
                resetdata();
            });
        } else {
            console.log("error submit!");
        }
    });
};
//表单END---------------------------------------



//图片上传----------------------
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
const imageUrl = ref("");

const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    
    ruleForm.images = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
        ElMessage.error("只能上传jpg或png格式的图片!");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("图片大小不能超过 2MB!");
        return false;
    }
    return true;
};

//上传end----------------------



const resetdata = () => {
    ruleForm.images = "";
    ruleForm.materialName = "";
    ruleForm.price = "";
    ruleForm.unitName = "";
    ruleForm.mnemonic = "";
    ruleForm.stock = "";
    ruleForm.barCode = "";
    ruleForm.id = "";
    isedit.value = true;
    title.value = "新增分类";
};

// 通过 defineExpose 暴露给父组件
defineExpose({
    showflag,
    title,
    isedit,
    device_id,
    ruleForm,
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
    margin-bottom: 30px;
}
:deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
}
:deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
